package com.tanhua.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.domain.Admin;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @author 阿鹏
 * @date 2021/2/18 22:38
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            response.setStatus(401);
            return false;
        }

        // 从请求头中获取token
        String token = authorization.replace("Bearer ", "");

        String adminJson = redisTemplate.opsForValue().get(CacheKey.TOKEN_PREFIX + token);
        if (StringUtils.isBlank(adminJson)) {
            response.setStatus(401);
            return false;
        }

        // 把当前用户绑定到线程
        Admin admin = JSON.parseObject(adminJson, Admin.class);
        AdminHolder.setAdmin(admin);
        AdminHolder.setToken(token);

        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX + token, JSON.toJSONString(admin), Duration.ofHours(1));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.removeAdmin();
        AdminHolder.removeToken();
    }
}
